<?php

// -- General function --

// redirect to $url
function redirectUrl($url) {
	header("Location: " . $url);
}

// redirect to file
function redirectFile($fileType, $fileName) {
	header("Content-type: " . $fileType);
	header("Content-disposition: attachment; filename=" . $fileName);
}

// format url query
function formatUrlQuery($query) {
	$encodedQuery = "";
	while (list($var, $val) = each($query)) {
		$encodedQuery .= ($var . "=" . urlencode($val) . "&");
	}
	return htmlentities(substr($encodedQuery, 0, strlen($encodedQuery)-1));
}

// transform a $pageName to full path
function getPath($pageName) {
	global $config;
	
	$pageName = str_replace("/", "", $pageName);
	return $config["data_dir"] . "/" . $pageName . ".html";
}

// read content from file
function getContent($path) {
	$file = @fopen($path, "rt");
	
	if ($file) {
		$content = fread($file, filesize($path) + 1);
		fclose($file);
		
		return $content;
	} else {
		return "";
	}
}

// write content to file (if content is empty, file is deleted)
function putContent($path, $content) {	
	if (strcmp($content, "")) {
		$file = @fopen($path, "wt");
		$content = fwrite($file, $content);
		fclose($file);
	} else {
		@unlink($path);
	}
}

// apply $expression to $content
// $expresion is an array of expression => array(method, replace object)
// method is 0 for str_replace(), 1 for preg_replace() and 2 for preg_replace_callback() 
function applyExpression($content, $expression) {
	while (list($match, $replace) = each($expression)) {
		switch ($replace[0]) {
			case 0: $content = str_replace($match, $replace[1], $content); break;
			case 1: $content = preg_replace($match, $replace[1], $content); break;
			case 2: $content = preg_replace_callback($match, $replace[1], $content); break;
			default: break;
		}
	}
	
	return $content;	
}

// return tick from system start
function getTick() {
	$tick = explode(' ', microtime());
	return $tick[1] + $tick[0];
}

// initialize session
function initializeSession() {
	global $config;
	
	@session_start();
	if (!isset($_SESSION[$config["session_key"]])) {
		$_SESSION[$config["session_key"]] = md5(session_id() . time());
	}
}

//check admin privilege
function checkAdminPrivilege() {
	global $config;
	
	return (   isset($_SESSION[$config["session_key"]]) 
			&& file_exists($config["data_dir"] 
						 . "/" . $config["login_page_dir"]
						 . "/" . $config["login_page_prefix"] . $_SESSION[$config["session_key"]]));
}


// -- View functions --

// format $pageContent using $expressionMap in order and additionaly text matching $ignoreExpression is not modified
function formatPageContent($pageContent, $expressionMap, $ignoreExpression) {
	if (strcmp($ignoreExpression, "")==0) $pageSplit = array($pageContent);
	else $pageSplit = preg_split($ignoreExpression, $pageContent, -1, PREG_SPLIT_DELIM_CAPTURE);
	
	$i=0; while ($i<count($pageSplit)) {
		$pageSplit[$i] = applyExpression($pageSplit[$i], $expressionMap);
		$i += 2;
	}
	
	$pageContent=""; while (list(,$e) = each($pageSplit)) $pageContent .= $e;
	
	return $pageContent;
}

// return formatted content of $pageName
function getPageContent($pageName) {
	global $config;

	$path = getPath($pageName);
	if (!file_exists($path)) $path = getPath($config["special_page_prefix"] . $config["view_error_page"]);
	
	$pageContent = getContent($path);
	
	if (strcmp($pageName, "menu") && strcmp($pageName, "sidemenu")) { // regular page format (put in the array)
		$pageContent = formatPageContent($pageContent, array(), "");
	} else { // menu page format
		$pageContent = formatPageContent($pageContent, array(), "");		
	}
	
	// all page format
	$pageContent = formatPageContent($pageContent, 
									 array(
											"\r" => array(0, ""), // CRLF => LF
											"/\[\[(.+?)\]\]/" => array(2, create_function('$a', 
																		  'return "<a href=\"index.php?". formatUrlQuery(array("action"=>"view", "page"=>$a[1])) . "\">$a[1]</a>"; ')), // internal [[link]]
										   ),
									 "/%%(.+?)%%/" // ignore
									);
									
	return $pageContent;
}

// return last modification date
function getPageDate($pageName) {
	global $config;

	$path = getPath($pageName);
	if (!file_exists($path)) return "";
	
	$stat = stat($path);	
	return strftime($config["date_format"], $stat[10]);	
}

// format $pageInfo
function formatPageInfo($pageName, $pageDate, $loadTime) {
	$pageInfo = "";
	
	if (strcmp($pageDate, "")) {
		$pageInfo = $pageInfo . sprintf("%s | ", $pageDate);
	}
	
	if (strcmp($pageName, "")) {
		if (checkAdminPrivilege()) {
			$pageInfo .= " privileges granted ";
			$pageInfo .= "(<a href=\"index.php?" . formatUrlQuery(array("action"=>"logout")) . "\">logout</a>";
			$pageInfo .= "|<a href=\"index.php?" . formatUrlQuery(array("action"=>"backup")) . "\">backup</a>) ";
			$pageInfo .= " (<a href=\"index.php?" . formatUrlQuery(array("action"=>"edit", "page"=>$pageName)) . "\">modify</a>";
			$pageInfo .= "|<a href=\"http://validator.w3.org/check/referer\">check</a>) ";
		} else {
			$pageInfo .= " <a href=\"index.php?" . formatUrlQuery(array("action"=>"login")) . "\">login</a> to modify";
		}
		$pageInfo .= " | ";
	}

	$pageInfo .= sprintf("%.3fs", $loadTime);	
	
	return $pageInfo;
}


// --  Edit function --

// return encoded content of $pageName
function getEncodedPageContent($pageName) {
	$path = getPath($pageName);
	if (!file_exists($path)) return "";
	
	$pageContent = getContent($path);
	
	return htmlspecialchars($pageContent);
}

// save page content in html format
function savePageContent($pageName, $encodedPageContent) {
	$path = getPath($pageName);
	
	putContent($path, stripslashes($encodedPageContent));
}


// -- Search functions --

// search page containing pattern
function searchPage($pattern) {
	global $config;

	$pattern = "/(.*)" . $pattern . "(.*)\.html$/i";
	
	$match = array();
	$dir = opendir($config["data_dir"]);
	while ($file = readdir($dir)) {
		if (   $file[0]!='.' 
			&& (checkAdminPrivilege() || strncmp($file, $config["special_page_prefix"], strlen($config["special_page_prefix"]))!=0)
			&& @preg_match($pattern, $file)) {
			
			$match[] = str_replace(".html", "", $file);
		}
	}
	
	if (count($match)==0) return "Nothing found";
	
	sort($match);	
	$pageContent = "";
	while (list(, $file) = each($match)) {
		$pageContent .= "<a href=\"index.php?action=view&page=$file\">$file</a><br />\n"; 
	}
	
	return $pageContent;	
}

// -- Backup functions --

function backupPages() {
	global $config;
	
	$dir = opendir($config["data_dir"] . "/" . $config["login_page_dir"]);
	while ($file = readdir($dir)) {
		if (   $file[0]!='.' 
			&& strncmp($file, "index", strlen("index"))
			&& strcmp($file, $config["login_page_prefix"] . $_SESSION[$config["session_key"]])) {
			@unlink($config["data_dir"] 
					. "/" . $config["login_page_dir"]
					. "/" . $file);
		}
	}	
	
	return passthru("tar cvf - " . $config["data_dir"] . " | gzip -c");
}


// -- Login/logout functions --

// check authentification data comparing with $config
function checkLogin($user, $pass) {
	global $config;
	
	return (strcmp($user, $config["username"])==0 && strcmp(sha1($config["passphase"] . $pass), $config["password"])==0);
}

// enable admin privilege
function enableAdminPrivilege() {
	global $config;	
	
	@touch($config["data_dir"] 
			. "/" . $config["login_page_dir"]
			. "/" . $config["login_page_prefix"] . $_SESSION[$config["session_key"]]);
}

// disable admin privilege
function disableAdminPrivilege() {
	global $config;
	
	@unlink($config["data_dir"]
			. "/" . $config["login_page_dir"]
			. "/" . $config["login_page_prefix"] . $_SESSION[$config["session_key"]]);
}

// -- Zz.zZ -- 

// this stands for writing funny stuffs on screen, put your own humour
function pwet() {
	echo "Pwet pwet pwet!!! <br />";
}

if (!isset($config)) pwet();

?>